// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
//@ts-ignore
import { activityApi } from '../../../api/activity'
import { authApi } from '../../../api/auth'
import { authLogin, checkAuth } from '/store/actions'
import { isLogin } from '/store/mutations'
import { GlobalData } from '/store/state'
import { $event, $logger, $storage } from '/utils'

Page({
  data: {
    isFullScreen: GlobalData.isFullScreen,
    cropper: '' as any,
    logoCropper: '' as any,
    creating: false,
    phone: '',
    agree: false,
    commodity_id: 0, // 关联的商品编号
    items: [
      { name: '后排199元座位', value: '199', margin: 2, commodity_id: 0 },
      { name: '后排299元座位', value: '299', margin: 2, commodity_id: 0 },
      { name: '中排399元座位', value: '399', margin: 2, commodity_id: 0 },
      { name: '前排1999元座位', value: '1999', margin: 2, commodity_id: 0 },
    ],
    bgParams: {
      width: 181,
      height: 253,
      max_width: 500,
      max_height: 714,
      export_scale: 1,
      disable_rotate: true,
      disable_ratio: true,
      limit_move: true,
      src: '' as string,
      show: false,
      scale: 1,
      imgSrc: '' as any,
    },
    typeData: [] as any[],
    goodsids_list: [] as any[],
    title: '',
    detail: '',
    code: '',
    /** 后端绑定账号所需内容 (来源于后端) */
    form: {} as BindUserPayload,
    date: '',
    location: '',
    type: 0,
    count: 1,
    remain_count: 999,
    price: 0.0,
    total_price: 0.0,
    /** 页面展示的时间格式 */
    dateShow: '',
    /** 详细地址 */
    address: '',
    isEditor: false,
    id: 0,
    /** 发布状态，防止抖动点击 */
    publishing: false,
    closeable: false,
  },
  reduce() {
    if (this.data.count < 2) return
    this.setData({
      count: this.data.count - 1,
    })
    this.getPrice()
  },
  add() {
    if (this.data.count < 5) {
      this.setData({
        count: this.data.count + 1,
      })
      this.getPrice()
    } else {
      wx.showToast({ title: '单次购买最多5张门票！', icon: 'none' })
      console.log(this.data.count)
    }
  },

  /** 计算金额 */
  getPrice() {
    if (this.data.count == 0) {
      this.setData({
        total_price: 0,
      })
    } else {
      // console.log(this.data.price)
      let total_1 = '0.0'
      let price_0 = this.data.price
      let price_0_string = this.data.price.toString()
      if (/\./.test(price_0_string)) {
        total_1 = (price_0 * this.data.count).toString()
        total_1 = parseFloat(total_1).toFixed(2)
      } else {
        total_1 = (price_0 * this.data.count).toString()
      }
      this.setData({
        total_price: parseFloat(total_1),
      })
    }
  },
  //  相应radio组件变化的函数 parseFloat
  async radioChange(e: any) {
    console.log(e)
    let price_0 = 0.0
    let price_0_string = '0.0'
    let total_1 = '0.0'
    let goods_id = 0
    let remain_count_show = 0
    for (let i = 0; i < this.data.goodsids_list.length; i++) {
      if (parseInt(e.detail.value) == this.data.goodsids_list[i].id) {
        price_0 = this.data.goodsids_list[i].price
        goods_id = this.data.goodsids_list[i].goods_id
        console.log(goods_id)
        remain_count_show =
          this.data.goodsids_list[i].sell_number - this.data.goodsids_list[i].sold_number
        if (remain_count_show < 0) {
          remain_count_show = 0
        }
        price_0_string = price_0.toString()
      }
    }
    if (/\./.test(price_0_string)) {
      total_1 = (price_0 * this.data.count).toString()
      total_1 = parseFloat(total_1).toFixed(2)
      console.log(total_1)
    } else {
      total_1 = (price_0 * this.data.count).toString()
    }

    this.setData({
      price: price_0,
      remain_count: remain_count_show,
      total_price: parseFloat(total_1),
      commodity_id: goods_id,
    })
  },
  async onLoad(query: { event_id: string }) {
    // console.log(query.event_id)
    const my_phone = GlobalData.phone
    console.log('my_phone is ' + my_phone)
    this.setData({
      phone: my_phone,
      isFullScreen: GlobalData.isFullScreen,
      // @ts-ignore
      cropper: this.selectComponent('#image-cropper'),
    })
    if (!isLogin()) {
      console.log('not login')
      await checkAuth()
    } else {
      console.log('login')
    }
    if (this.data.phone === '') {
      await checkAuth()
    }
    const eventDetail = await activityApi.getActivity(parseInt(query.event_id))
    eventDetail.date = eventDetail.date.slice(0, 10)
    const eventPriceDetail = await activityApi.getActivityDetail(parseInt(query.event_id))
    const obj_all = []
    let remain_count_show = 0
    if (eventPriceDetail) {
      for (const iterator of eventPriceDetail) {
        const obj = {
          id: iterator.id,
          goods_id: iterator.commodity_id,
          sell_number: iterator.sell_number,
          sold_number: iterator.sold_number,
          price: parseFloat(iterator.ticket_price),
        }
        remain_count_show = iterator.sell_number - iterator.sold_number
        if (remain_count_show < 0) {
          remain_count_show = 0
        }
        obj_all.push(obj)
        if (iterator.is_default == 1) {
          iterator.checked = true
          this.setData({
            price: parseFloat(iterator.ticket_price),
            remain_count: remain_count_show,
            total_price: parseFloat(iterator.ticket_price),
            commodity_id: iterator.commodity_id,
          })
          this.getPrice()
        } else {
          iterator.checked = false
        }
      }
      this.setData({
        eventPriceDetail: eventPriceDetail,
        eventDetail: eventDetail,
        goodsids_list: obj_all,
        phone: this.data.phone,
      })
    }
  },

  async getWechatUserPhone(e: WechatMiniprogram.CustomEvent) {
    const detail = e.detail
    console.log(detail)
    if (detail.errMsg !== 'getPhoneNumber:ok') {
      wx.showToast({
        title: detail.errMsg,
        icon: 'none',
      })
      return
    } else {
      console.log('getPhoneNumber:ok')
    }
    try {
      const registerInfo = $storage.get('registerInfo') as GetUserAccountRegisterCallback
      console.log(this.data.form)
      console.log(registerInfo)
      const formdata = this.data.form
      const openid = formdata['openid']
      const params = {
        appid: openid,
        encryptedData: detail.encryptedData,
        iv: detail.iv,
        payload: registerInfo.payload,
        decrypt: registerInfo.decrypt,
        openid: registerInfo.openid,
      }
      console.log(params)
      const res = await authApi.bindUser({
        ...this.data.form,
        encryptedData: detail.encryptedData,
        iv: detail.iv,
        payload: registerInfo.payload,
        decrypt: registerInfo.decrypt,
        openid: registerInfo.openid,
      })
      console.log(res)
      // if (res.type === 'alert') {
      //   wx.showModal({
      //     title: '错误',
      //     content: res.message,
      //   })
      //   return
      // }
      // setAccessToken(res.token, res.expires_in)
      // // $storage.remove('registerInfo') // 2024/7/24日修改
      // $event.emit('after:registerInfo')
      // await getDomoUser()
      // $event.emit('after:login')
    } catch (error) {
      $logger.debug('login error', error)
    }
  },

  async getDomoUser(res: WechatMiniprogram.GetUserInfoSuccessCallbackResult) {
    wx.showLoading({ title: '正在登录' })
    try {
      const isLogin = await authLogin(this.data.code, res)
      if (isLogin) {
        $event.emit('after:login')
      }
    } catch (error) {
      wx.showToast({
        title: error.data.message,
        icon: 'none',
      })
    }
    wx.hideLoading()
  },
  goback() {
    wx.navigateBack()
  },
  async doSubmit() {
    if (!this.data.agree) {
      wx.showToast({
        title: '请先同意购买协议才能购买门票！',
        icon: 'none',
        duration: 1000,
      })
    } else {
      if (!this.data.commodity_id) {
        wx.showToast({
          title: 'commodity_id参数错误',
          icon: 'none',
          duration: 1000,
        })
      } else {
        if (!isLogin()) {
          await checkAuth()
        }
        const commodityId = this.data.commodity_id
        const buy_count = this.data.count
        const buy_total_price = this.data.total_price
        wx.navigateTo({
          url: `/pages/match/pay/pay?commodityId=${commodityId}&orig=1&count=${buy_count}&total_price=${buy_total_price}`,
        })
      }
    }

    console.log(this.data.commodity_id)
    // commodityId
  },
  handleBgTap() {
    wx.chooseImage({
      sizeType: ['compressed'],
      success: ({ tempFilePaths: { [0]: path } }) => {
        this.setData({
          bgParams: {
            ...this.data.bgParams,
            src: path,
            show: true,
          },
        })
      },
    })
  },
  onChange: function (e: any) {
    console.log(e.detail.value)
    let checkedValues = e.detail.value
    this.setData({
      agree: checkedValues,
    })
    // 在这里可以进行其他操作，例如发送请求、更新数据等
  },
  /** 取消选择图片 */
  cancel() {
    this.setData({
      bgParams: {
        ...this.data.bgParams,
        show: false,
      },
    })
  },
  loadimage() {
    wx.hideLoading()
    this.data.cropper.imgReset()
  },
  clickcut(e: any) {
    //图片预览
    wx.previewImage({
      current: e.detail.url, // 当前显示图片的http链接
      urls: [e.detail.url], // 需要预览的图片http链接列表
    })
  },
  submitBg() {
    this.data.cropper.getImg((obj: any) => {
      this.setData({
        bgParams: {
          ...this.data.bgParams,
          imgSrc: obj,
          show: false,
        },
      })
    })
  },
  /** 标题 */
  inputTitle(e: WechatMiniprogram.CustomEvent) {
    const {
      detail: { value },
    } = e
    this.setData({
      title: value,
    })
  },
  /** 详情 */
  toEditor() {
    wx.navigateTo({
      url: '/pages/editor/editor?type=activity',
    })
  },
  /** 日期 */
  bindDateChange(e: WechatMiniprogram.CustomEvent) {
    const {
      detail: { value },
    } = e
    if (new Date().getTime() - new Date(value).getTime() > 0) {
      wx.showToast({
        title: '活动日期必须大于当前日期',
        icon: 'none',
        duration: 1000,
      })
      return
    }
    const date = value + ' 00:00:00'
    this.setData({
      date,
      dateShow: value,
    })
  },
  /** 价格 */
  inputPrice(e: WechatMiniprogram.CustomEvent) {
    const {
      detail: { value },
    } = e
    this.setData({
      price: value * 100,
    })
  },
  /** 分类 */
  chooseType(e: WechatMiniprogram.CustomEvent) {
    const {
      currentTarget: {
        dataset: { id },
      },
    } = e
    this.setData({
      type: id,
    })
  },
  toLocaltion() {
    wx.navigateTo({
      url: '/pages/activity/location/location',
    })
  },
  /** 发布 */
  async toSubmit() {},
})
